import ArrayPrototype from './ArrayPrototype.js'

/**
 * 为对象设置拦截器
 */
export default class Observer {
    constructor(data) {
        this.walk(data)
    }
    walk(data) {
        if (typeof data !== 'object' || data == null) return
        //为数组改变原型，目的是对push等方法添加的新对象进行拦截
        if (Array.isArray(data)) {
            Object.setPrototypeOf(data, ArrayPrototype)
        }

        Object.keys(data).forEach(key => {
            this.defineReactive(data, key, data[key])
        })
    }
    defineReactive(obj, key, value) {
        this.walk(value)
        Object.defineProperty(obj, key, {
            //读取对象属性
            get() {
                return value
            },
            //设置属性
            set: newValue => {
                if (newValue == value) return
                this.walk(newValue)
                value = newValue
            },
        })
    }
}
